<?php
// +----------------------------------------------------------------------
// | Iecms [ Make the most exquisite CMS ]
// +----------------------------------------------------------------------
// | Copyright (c) 2009~2019 http://www.iemoo.com All rights reserved.
// +----------------------------------------------------------------------
// | Author: iemoo <i@iemoo.com>
// +----------------------------------------------------------------------
// | DateTime: 2019/11/19 11:08
// +----------------------------------------------------------------------
namespace app\admin\controller;

use app\common\model\Archives as ArchivesModel;
use app\common\model\Category as CategoryModel;
use app\common\model\ArchivesFiles as ArchivesFilesModel;
use app\common\model\Files as FilesModel;


use app\admin\validate\Archives as ArchivesValidate;
use app\admin\validate\ArchivesFiles as ArchivesFilesValidate;
use think\exception\ValidateException;

use think\facade\Request;
use think\facade\View;
use think\facade\Config;

/**
 * 内容管理
 * Class AdminUser
 * @package app\admin\controller
 */
class Archives extends Base
{

	//所有栏目分类
    public function __construct()
    {
        parent::__construct();

		$category_list	= CategoryModel::order('sort desc,id asc')->select();
		$category_list	= $category_list->toArray();
        $category_list_tree = tree_cate($category_list);
		View::assign('category_list_tree',$category_list_tree);
		
    }
 
    /**
     * 内容管理
     * @return mixed
     */
    public function index()
    {
		$Archives_list = ArchivesModel::order('sort desc,id desc')->paginate(10);
		View::assign('Archives_list',$Archives_list);

		return View::fetch('index');
    }


    /**
     * 分类内容列表
     * @return mixed
     */
    public function lists()
    {
		
		$request = Request::param();
		$real_request = array_filter($request);

		if(!isset($real_request['category_id'])){
			return redirect('/admin/Archives/index');		
		}

		//获取所有子分类ID		
		$Archives_list = ArchivesModel::withSearch(['category_id','title'], $real_request)->order('sort desc,id desc')->paginate([
			'query'     => $real_request,
			'list_rows' => 10,
		]);

		$category	= CategoryModel::find($real_request['category_id']);

		View::assign('Archives_list',$Archives_list);

		View::assign('category',$category);
		return View::fetch('lists');
    }


    /**
     * 添加内容
     * @return mixed
     */
    public function add()
    {
		$category_id = Request::param('category_id');

		if (Request::isPost()) {

			$data = Request::only(['category_id', 'title', 'images', 'keywords', 'description', 'content', 'author', 'source', 'hits', 'sort', 'status']);

            try {
				validate(ArchivesValidate::class)->check($data);
			} catch (ValidateException $e) {
				// 验证失败 输出错误信息
				$this->error($e->getError());
			}
			
			$archives = ArchivesModel::create($data);
			if (!$archives->isEmpty()) {
				//更新文件
				if(isset($data['images']) && is_array($data['images'])){
					//有新的文件
					if(!empty($data['images'])){						
						foreach($data['images']['id'] as $key => $val){
							
							$archives_files = array();
							$archives_files['archives_id'] = $archives->id;
							$archives_files['files_id'] = $val;
							$archives_files['name'] = $data['images']['name'][$key];
							$archives_files['title'] = $data['images']['title'][$key];
							$archives_files['sort'] = $key;

							ArchivesFilesModel::create($archives_files);
						}
					}

				}
				$this->success('保存成功',url('admin/Archives/index'));
			} else {
				$this->error('保存失败');
			}

        }

		View::assign('category_id',$category_id);
		return View::fetch('add');
    }


    /**
     * 编辑内容
     * @param $id
     * @return mixed
     */
    public function edit($id)
    {

		if (Request::isPost()) {

			$data = Request::only(['id', 'category_id', 'title', 'images', 'keywords', 'description', 'content', 'author', 'source', 'hits', 'sort', 'status']);

			if(isset($data['images']) && is_array($data['images'])){

				//已有文件的ID
				$uploads_ids = ArchivesFilesModel::where('archives_id',$id)->column('files_id');
				//获取差集
				$diff_new = array_diff($data['images']['id'], $uploads_ids);	
				//获取差集
				$diff_old = array_diff($uploads_ids, $data['images']['id']);	
				
				//如果有差集，说明有新的文件
				if(!empty($diff_new)){
					foreach($diff_new as $key => $val){							
						$archives_files = array();
						$archives_files['archives_id'] = $id;
						$archives_files['files_id'] = $val;
						$archives_files['name'] = $data['images']['name'][$key];
						ArchivesFilesModel::create($archives_files);
					}
				}

				//如果有差集，说明有要删除的文件
				if(!empty($diff_old)){
					foreach($diff_old as $key => $val){						
						ArchivesFilesModel::where('archives_id',$id)->where('files_id',$val)->delete();					
					}
				}

				//更新图片标题
				foreach($data['images']['id'] as $key => $val){	
					$fiels_updata = ArchivesFilesModel::where('archives_id',$id)->where('files_id',$val)->find();	
					$fiels_updata->title = $data['images']['title'][$key];
					$fiels_updata->sort = $key;
					$fiels_updata->save();									
				}

			}else{
				//也可能是要把图片都删除完
				ArchivesFilesModel::where('archives_id',$id)->delete();
			}

            try {
				validate(ArchivesValidate::class)->check($data);
			} catch (ValidateException $e) {
				// 验证失败 输出错误信息
				$this->error($e->getError());
			}

			if (ArchivesModel::update($data, ['id' => $id])) {
				$this->success('更新成功');
			} else {
				$this->error('更新失败');
			}

        }


        $archives = ArchivesModel::find($id);		
		$images = $archives->files->toArray();		
	
		View::assign('info',$archives);
		View::assign('images',$images);

		return View::fetch('edit');
    }

    /**
     * 删除内容
     * @param $id
     */
    public function delete($id)
    {
        if (ArchivesModel::destroy($id)) {
            $this->success('删除成功');
        } else {
            $this->error('删除失败');
        }
    }
}